package com.studentmanagement.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.studentmanagement.dao.EnrollmentMapper;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.PageBean;
import com.studentmanagement.service.EnrollmentService;

@Service
@Transactional
public class EnrollmentServiceImpl implements EnrollmentService {

    @Autowired
    private EnrollmentMapper enrollmentMapper;

    @Override
    public boolean addEnrollment(Enrollment enrollment) {
        return enrollmentMapper.insertEnrollment(enrollment) > 0;
    }

    @Override
    public boolean updateEnrollment(Enrollment enrollment) {
        return enrollmentMapper.updateEnrollment(enrollment) > 0;
    }

    @Override
    public boolean deleteEnrollment(Integer enrollmentId) {
        return enrollmentMapper.deleteEnrollment(enrollmentId) > 0;
    }

    @Override
    @Transactional(readOnly = true)
    public Enrollment getEnrollmentById(Integer enrollmentId) {
        return enrollmentMapper.selectEnrollmentById(enrollmentId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Enrollment> getAllEnrollments() {
        return enrollmentMapper.selectAllEnrollments();
    }

    @Override
    @Transactional(readOnly = true)
    public PageBean<Enrollment> getEnrollmentsByPage(int pageNum, int pageSize, String sortField, String sortOrder) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 设置排序参数
        Map<String, Object> params = new HashMap<>();
        params.put("sortField", sortField);
        params.put("sortOrder", sortOrder);

        // 查询数据
        List<Enrollment> enrollments = enrollmentMapper.selectEnrollmentsByPage(params);

        // 获取分页信息
        PageInfo<Enrollment> pageInfo = new PageInfo<>(enrollments);

        // 封装分页结果
        PageBean<Enrollment> pageBean = new PageBean<>();
        pageBean.setPageNum(pageInfo.getPageNum());
        pageBean.setPageSize(pageInfo.getPageSize());
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        pageBean.setList(pageInfo.getList());
        pageBean.setSortField(sortField);
        pageBean.setSortOrder(sortOrder);

        return pageBean;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Enrollment> getEnrollmentsByStudentId(Integer studentId) {
        return enrollmentMapper.selectEnrollmentsByStudentId(studentId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Enrollment> getEnrollmentsByCourseId(Integer courseId) {
        return enrollmentMapper.selectEnrollmentsByCourseId(courseId);
    }
}